/**
 * way:开发环境与测试环境
 * */
const utils = require('../utils')
const webpack = require('webpack')
const config = require('../../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('../webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({sourceMap: config.dev.cssSourceMap, usePostCSS: true})
  },
  devtool: config.dev.devtool,
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        {from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html')},
      ],
    },
    noInfo: true,
    compress: true,
    contentBase: path.join(__dirname, "build"),
    // contentBase:false,
    hot: true,   //开启热更新热替换
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? {warnings: false, errors: true}
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true,
    watchOptions: {
      poll: config.dev.poll,
    },
    proxy: {
      "work-manage-server": {
        target: "https://test.glsc.com.cn:12204/work-manage-server",
        changeOrigin: true,
        pathRewrite: {
          "^/work-manage-server": "",
        },
      },
    }
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      'process.env': require('../../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      //打包生成的文件名
      filename: 'index.html',
      //指定模板的位置
      template: 'public/index.html',
      //设置网页的图标(图标在在最外层)
      // favicon:'favicon.ico',
      inject: true,
      //是否把打包好的资源插入到页面中，是否设置hash值
      // hash: true,
      minify: {
        // removeComments: true, //在内存中html中就没有注释
        // collapseWhitespace: true, //清理html中的空格、换行符
        // minifyCSS: true, //压缩内部样式
        // removeEmptyElements: true, //清楚掉空标签
      }
    }),
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port
      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
          ? utils.createNotifierCallback()
          : undefined
      }))
      resolve(devWebpackConfig)
    }
  })
})
